package double_pointer;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 86185
 * Date: 2023-12-01
 * Time: 23:28
 */
public class FourNumSum {
    public static List<List<Integer>> fourSum(int[] nums, int target) {
        Arrays.sort(nums);
        List<List<Integer>> lists = new ArrayList<>();
        int n = nums.length;
        int i = 0;
        while(i < n - 3) {
            if(nums[i] > 0 && nums[i] > target) {
                break;
            }
            //固定数a
            int a = nums[i];
            long targetA = target - a;
            int j = i + 1;
            while (j < n - 2) {
                if(nums[j] > 0 && nums[j] > targetA) {
                    break;
                }
                //固定数b
                int b = nums[j];
                long targetB = targetA - b;
                int left = j + 1;
                int right = n - 1;
                while (left < right) {
                    int sum = nums[left] + nums[right];
                    if(sum < targetB) {
                        left++;
                    } else if (sum > targetB) {
                        right--;
                    } else {
                        lists.add(Arrays.asList(a, b, nums[left], nums[right]));
                        left++;
                        right--;
                        //去重, 不能越界
                        while (left < right && nums[left] == nums[left - 1]) {
                            left++;
                        }
                        while (left < right && nums[right] == nums[right + 1]) {
                            right--;
                        }
                    }
                }
                //去重, 不能越界
                j++;
                while (j < n - 2 && nums[j] == nums[j - 1]) {
                    j++;
                }
            }
            //去重, 不能越界
            i++;
            while (i < n - 3 && nums[i] == nums[i - 1]) {
                i++;
            }
        }
        return lists;
    }

    public static void main(String[] args) {
        System.out.println(fourSum(new int[]{1000000000,1000000000,1000000000,1000000000}, -294967296));
    }
}
